package cn.zj.smart.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

/**
 * 操作文件和目录
 *
 * @author xi.yang(xi.yang@downjoy.com)
 * @create 2018-07-04 下午 1:19
 **/
public class FileUtil {
    private static final Logger logger = LoggerFactory.getLogger(FileUtil.class);

    public static String getUserDir() {
        return System.getProperty("user.dir");
    }

    /**
     * 根据多个文件夹名获取path
     * @param dirs
     * @return
     */
    public static String getPath(String... dirs) {
        StringBuffer sb = new StringBuffer();
        for (String dir : dirs) {
            sb.append(dir).append(File.separator);
        }
        return sb.toString().substring(0, sb.toString().length() - 1);
    }

    public static void mkdirs(String dirsPath) {
        File file = new File(dirsPath);
        if (!file.exists()) {
            file.mkdirs();
        }
    }

    public static String[] getFileNames(String path) {
        File file = getFile(path);
        return file.list();
    }

    public static void replaceLineStr(Path readPath, Path writePath, String oldStr, String replaceStr) {
        try {
            BufferedReader bufferedReader = Files.newBufferedReader(readPath);
            BufferedWriter bufferedWriter = Files.newBufferedWriter(writePath);
            String line = bufferedReader.readLine();
            while (line != null) {
                line = line.replace(oldStr, replaceStr);
                bufferedWriter.write(line);
                bufferedWriter.newLine();
                line = bufferedReader.readLine();
            }
            bufferedReader.close();
            bufferedWriter.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static File getFile(String filePath) {
        try {
            int index = 0;
            filePath = filePath.replace("\\\\", File.separator).replace("\\/",File.separator).replace("\\", File.separator).replace("/",File.separator);
            if (filePath.lastIndexOf(File.separator) > 0) {
                index = filePath.lastIndexOf(File.separator);
            }
            if (index > 0) {
                String pathName = filePath.substring(0, index);
                File file = new File(pathName);
                if (!file.exists()) {
                    file.mkdirs();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("getFile error : {}", e.getMessage());
        }
        return new File(filePath);
    }

    public static void writeFileAppend(String filePath,String content) {
        try {
            FileWriter fileWriter = new FileWriter(getFile(filePath),true);
            fileWriter.write(content);
            fileWriter.close();
        } catch (Exception e) {
            logger.error("writeFileAppend error : {}", e.getMessage());
            e.printStackTrace();
        }
    }

    public static void writeFile(String filePath,String content) {
        try {
            FileWriter fileWriter = new FileWriter(getFile(filePath));
            fileWriter.write(content);
            fileWriter.close();
        } catch (Exception e) {
            logger.error("writeFile error : {}", e.getMessage());
            e.printStackTrace();
        }
    }

    public static String readFile(String filePath) {
        try {
            return new String(Files.readAllBytes(Paths.get(filePath)));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static List<String> readLine(Path path) {
        try {
            return Files.readAllLines(path, StandardCharsets.UTF_8);
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("read line error : " + path.toString());
        }
    }

    public static List<String> readLine(Path path, Charset charset) {
        try {
            return Files.readAllLines(path, charset);
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("read line error : " + path.toString());
        }
    }

    /**
     * 保存序列化对象
     * @param path
     * @param object
     */
    public static void writeObject(String path,Object object) {
        try {
            ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream(getFile(path)));
            outputStream.writeObject(object);
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 读取序列化对象
     * @param path
     * @return
     */
    public static Object readObject(String path) {
        try {
            File file = new File(path);
            if (!file.exists()) {
                return null;
            }
            ObjectInputStream inputStream = new ObjectInputStream(new FileInputStream(getFile(path)));
            Object object = inputStream.readObject();
            inputStream.close();
            return object;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
